home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 1726 < prev    next >
Encoding:
Text File  |  1996-08-06  |  2.1 KB  |  55 lines

  1. Path: winternet.com!not-for-mail
  2. From: jdege@winternet.com (Jeff Dege)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Fishing for Opinions:  Global Variables in GUI
  5. Date: 12 Jan 1996 15:49:42 GMT
  6. Organization: StarNet Communications, Inc
  7. Message-ID: <4d5vum$el4@blackice.winternet.com>
  8. References: <4cjg9c$m92@crchh327.rich.bnr.ca> <4d3o7o$d9m@news.bridge.net> <30f657d7.2731554@ixnews1.ix.netcom.com>
  9. NNTP-Posting-Host: klondike.winternet.com
  10. X-Newsreader: TIN [UNIX 1.3 950726BETA PL0]
  11.  
  12. On Fri, 12 Jan 1996 12:59:08 GMT, n4jvp (n4jvp@ix.netcom.com) wrote:
  13. :     To avoid using globals in multi-module programs I have been
  14. : using the extern keyword within the specific functions needing access
  15. : to the globals i.e.
  16. : [...]
  17. : Is this a good practice or is there a better way to do it? 
  18.  
  19.     Well, you're still using globals, you're just hiding access to them.
  20. My biggest problem with this is the separation between declaration and
  21. definition.  You have type-safety in C and C++ _only_ if every variable
  22. definition is identical.  The only way to ensure this is to require that
  23. there only be _one_ definition of a global variable.  Generally, this
  24. is done with header files.
  25.  
  26. // globals.h
  27. extern short TheGlobalWidgetCount;
  28.  
  29. // globals.cpp
  30. #include "globals.h"
  31. short TheGlobalWidgetCount = 0;
  32.  
  33. // stuff.cpp
  34. #include "globals.h"
  35. ...
  36.    TheGlobalWidgetCount += 1;
  37. ...
  38.  
  39.    If I should change the type of TheGlobalWidgetCount from short to long,
  40. I need to change it in two places, globals.h and globals.cpp, and the
  41. compiler will complain if I don't.  If I have extern declarations scattered
  42. all over my code, I need to change each and every one of them, and the
  43. compiler won't catch those I miss.  The program will simply crash at runtime.
  44.  
  45. -- 
  46.         "I quite agree with you," said the Duchess; "and the moral of
  47. that is -- `Be what you would seem to be' -- or, if you'd like it put
  48. more simply -- `Never imagine yourself not to be otherwise than what it
  49. might appear to others that what you were or might have been was not
  50. otherwise than what you had been would have appeared to them to be
  51. otherwise.'"
  52.                 -- Lewis Carrol, "Alice in Wonderland"
  53.  
  54.  
  55.